<script setup>
	import {reactive, toRefs, ref} from 'vue'
    import roleApi from '@/api/sys/role'

	const rules = reactive({
		name: [
			{required: true, message: '请输入角色名称', trigger: 'blur'}
		],
		code: [
			{required: true, message: '请输入唯一编码', trigger: 'blur'}
		]
	})

    //获取父组件的属性
    const props = defineProps({
        editDrawer: Boolean
    })
    const {editDrawer} = toRefs(props)

    //调用父组件的closeHandler方法
    const emits = defineEmits(['closeHandler'])
    //hasChange为true，需要更新列表
    const closeDrawer = (hasChange) => {
        emits('closeHandler',hasChange)
    }

    const editForm = ref({})
    //将子组件的init方法暴露给父组件
    const init = (id) => {
        if (id) {
            roleApi.getRoleDetailsById(id).then(response => {
                editForm.value = response.data
            })
        }else {
            editForm.value = {}
        }
    }
    defineExpose({init})

    //提交表单
    import { ElMessage } from 'element-plus'
    const ruleForm = ref(null)
    const submitForm = () => {
        ruleForm.value.validate((valid) => {
            if (valid) {
                if(!editForm.value.id){
                    roleApi.saveRole(editForm.value).then(response => {
                        ElMessage({type: 'success',message: '操作成功',})
                        closeDrawer(true)
                    })
                }else {
                    roleApi.updateRole(editForm.value).then(response => {
                        ElMessage({type: 'success',message: '操作成功',})
                        closeDrawer(true)
                    })
                }
            }
        })
    }
</script>

<template>
	<!--新增对话框-->
	<el-drawer
			title="编辑"
			width="600px"
            v-model="editDrawer"
            :before-close="closeDrawer"
	>

		<el-form :model="editForm" :rules="rules" ref="ruleForm" label-width="100px"
		         class="demo-editForm">
			<el-input v-model="editForm.id" autocomplete="off" type="hidden"></el-input>

			<el-form-item label="角色名称" prop="name" label-width="100px">
				<el-input v-model="editForm.name" autocomplete="off"></el-input>
			</el-form-item>

			<el-form-item label="唯一编码" prop="code" label-width="100px">
				<el-input v-model="editForm.code" autocomplete="off"></el-input>
			</el-form-item>

			<el-form-item label="描述" prop="remark" label-width="100px">
				<el-input v-model="editForm.remark" autocomplete="off"></el-input>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" @click="submitForm('editForm')">确 定</el-button>
				<el-button @click="emits('closeHandle')">关 闭</el-button>
			</el-form-item>
		</el-form>

	</el-drawer>
</template>
